﻿$(function () {
    //2.初始化页面
    var oPageInit = new PageInit();
    oPageInit.Init();
});

var PageInit = function () {
    var oInit = new Object();
    var postdata = {};

    var table, form, layer, element, upload;
    var active;
    var tableId = 'tb_list';
    //初始化页面上面的按钮事件
    oInit.Init = function () {
        layui.use(['table', 'element', 'upload'], function () {
            table = layui.table
          , form = layui.form
          , element = layui.element
          , upload = layui.upload
          , layer = layui.layer;

            oInit.loadData();

            oInit.LoadPageData();
        });

    }

    //初始化Table,加载数据
    oInit.loadData = function () {
        //方法级渲染
        table.render({
            elem: '#' + tableId
            , id: tableId
        , loading: true
        , toolbar: '#toolbar'
        , defaultToolbar: ['']  //工具栏右侧的图标按钮
        , url: Root + 'FZParam/GetBaseParam'
        , cols: [[
        { checkbox: true, fixed: true }, { type: 'numbers', title: '序号' }
        , { field: 'id', title: 'ID', sort: true, fixed: true, hide: true }
        , {
            field: 'name',
            title: '参数名称'
        }, {
            field: 'descs',
            title: '描述'
        }, {
            field: 'type',
            title: '参数类别',
            formatter: function (value, row, index) {
                return ShowParamType(value);
            }
        }
            , { fixed: 'right', title: '操作', toolbar: '#tableBar', width: 120 }
        ]]
        , page: true
        , limit: 10
            //, cellMinWidth: 80
        , height: 'full-300'
        });

        var $ = layui.$;
        active = {
            reload: function () {
                var txt_search = $('#txt_search');
                var temp = {
                    SearchText: txt_search.val(),
                    type: sel_type.getValue('value'),
                };

                //执行重载
                table.reload(tableId, {
                    method: 'post',
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                  , where: temp
                }, 'data');
            }
        };

        $('#formSearch .layui-btn').on('click', function () {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });

        zpActive.tableTool(table, layer, form, null, null, null, null, oInit.Delete, oInit.LoadTypeInit);

        //监听提交
        form.on('submit(save)', function (data) {
            var rs = oInit.Save(data.field);    //保存数据
            if (rs) {
                active.reload();    //重新加载table数据
                layer.closeAll();   //关闭弹出层
            }
            return false;   //true刷新当前页面
        });
    }

    oInit.LoadPageData = function () {
        $.ajax({
            type: "post",
            //async: false,
            url: Root + 'EPHonor/GetTitleFile',
            data: { ht_id: $('#ht_id').val() },
            success: function (result) {
                if (result.SubmitResult) {
                    //加载：企业荣誉对应的附件
                    var list = result.Object;
                    if (list == null || list.length == 0) {
                        return;
                    }
                    var uploadContainer = $('#uploadContainer');

                    var title_html = '';
                    var file_table_html = '';
                    var isExist = false;
                    var title_idx = 1; //每个标题前面的序号
                    $.each(list, function (i, item) {
                        file_table_html = '';
                        var item_title_files = $.grep(list, function (child) {
                            return child.ht_type1_file != null && child.ht_type1_file.ft_id == item.ht_type1_title.ft_id;
                        });//fl_phy_add
                        $.each(item_title_files, function (j, child) {
                            var uploadIndex = ['upload-', child.ht_type1_file.ep_id, child.ht_type1_file.ht_id, child.ht_type1_file.ft_id, '-', j].join('');
                            if ($('#' + uploadIndex).length > 0) {
                                isExist = true; //相同的附件标题已经添加过，则过滤掉
                                return;
                            }
                            file_table_html += //'<tr id="' + uploadIndex + '"><td>' + child.ht_type1_file.fl_name + '</td>'
                                '<tr id="' + uploadIndex + '"><td><a style="color: #5FB878;" target="_blank" href="/TempFile/ZPJ/upload/' + child.ht_type1_file.fl_phy_add + '">' + child.ht_type1_file.fl_name + '</a></td>'
                                + '<td style="display: none;">12.3kb</td><td><span style="color: #5FB878;">上传成功</span></td>'
                                + '<td><button class="layui-btn layui-btn-xs layui-btn-danger demo-delete" data-fileid="' + child.ht_type1_file.id + '">删除</button></td></tr>';
                        });
                        if (isExist) {
                            isExist = false;
                            return;
                        }

                        var tbody_fileListId = 'tbody_fileList' + i;
                        var btn_selectId = 'btn_select' + i;
                        var btn_uploadId = 'btn_uploadId' + i;
                        title_html = ['<div class="layui-colla-item">'
                            , '<h2 class="layui-colla-title" ' + (item_title_files.length > 0 ? 'style="color:green;"' : '') + ' >' + title_idx + '.' + item.ht_type1_title.ft_title + '</h2>'
                            , '<div class="layui-colla-content">'
                                , '<div class="layui-upload">'
                                    , '<button type="button" class="layui-btn layui-btn-normal layui-btn-sm" id="' + btn_selectId + '">选择多文件</button>'
                                    , '<input class="layui-upload-file" type="file" accept="" name="file" multiple="">'
                                    , '<div class="layui-upload-list">'
                                        , '<table class="layui-table">'
                                            , '<thead>'
                                                , '<tr>'
                                                    , '<th>文件名</th>'
                                                    , '<th style="display: none;">大小</th>'
                                                    , '<th width="15%">状态</th>'
                                                    , '<th width="20%">操作</th>'
                                                , '</tr>'
                                            , '</thead>'
                                            , '<tbody id="' + tbody_fileListId + '">' + file_table_html + '</tbody>'
                                        , '</table>'
                                    , '</div>'
                                    , '<button type="button" class="layui-btn layui-btn-sm" id="' + btn_uploadId + '" data-ftid="' + item.ht_type1_title.ft_id + '"><i class="layui-icon layui-icon-upload"></i>开始上传</button>'
                                , '</div>'
                            , '</div>'
                        , '</div>'].join('');
                        title_idx++;
                        uploadContainer.append(title_html);
                        //初始化上传按钮
                        oInit.InitUpload(tbody_fileListId, btn_selectId, btn_uploadId);
                    });

                    $('.demo-delete').on('click', function () {
                        var fileid = $(this).data('fileid');
                        var deleteBtnObj = $(this);
                        if (fileid && fileid.length > 0) {
                            dialog.confirm('确认删除该附件吗？附件删除后将不再显示。', function (confirm_index) {
                                oInit.Delete(fileid, function () {
                                    deleteBtnObj.parent().parent().remove();
                                });
                            });
                        }
                    });

                } else {
                    dialog.danger(result.Message);
                }
            },
            error: function () {
                dialog.danger('操作失败！请重试或者联系管理员');
            },
            complete: function () {
                element.render('collapse');
            }
        });
    }

    oInit.InitUpload = function (tbody_fileListId, btn_selectId, btn_uploadId) {
        var ft_id = $('#' + btn_uploadId).data('ftid');
        var ht_id = $('#ht_id').val();
        var temp = {
            ht_id: ht_id,
            ft_id: ft_id,
        };
        //多文件列表示例
        var demoListView = $('#' + tbody_fileListId)
        , uploadListIns = upload.render({
            elem: '#' + btn_selectId
          , url: Root + 'EPHonor/UploadEPAnnex' //改成您自己的上传接口
          , data: temp
          , accept: 'file'
          , multiple: true
          , auto: false
          , bindAction: '#' + btn_uploadId
          , choose: function (obj) {
              var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
              //读取本地文件
              obj.preview(function (index, file, result) {
                  var tr = $(['<tr id="upload-' + index + '">'
                    , '<td>' + file.name + '</td>'
                    //, '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                    , '<td>等待上传</td>'
                    , '<td>'
                      , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                      , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                    , '</td>'
                  , '</tr>'].join(''));

                  //单个重传
                  tr.find('.demo-reload').on('click', function () {
                      obj.upload(index, file);
                  });

                  //删除TR
                  tr.find('.demo-delete').on('click', function () {
                      var deleteBtnObj = $(this);
                      var fileid = deleteBtnObj.data('fileid');
                      if (fileid && fileid.length > 0) {
                          dialog.confirm('确认删除该附件吗？附件删除后将不再显示。', function (confirm_index) {
                              oInit.Delete(fileid, function () {
                                  delete files[index]; //删除对应的文件
                                  tr.remove();
                                  uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                              });
                          });
                      } else {
                          //未上传到服务器直接允许删除
                          delete files[index]; //删除对应的文件
                          tr.remove();
                          uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                      }
                  });
                  demoListView.append(tr);
              });
          }
          , done: function (res, index, upload) {
              if (res.SubmitResult) { //上传成功
                  var tr = demoListView.find('tr#upload-' + index)
                  , tds = tr.children();
                  tds.eq(0).html('<a style="color: #5FB878;" href="/TempFile/ZPJ/upload/' + res.FilePath + '" target="_blank">' + res.FileName + '</a>');
                  tds.eq(1).html('<span style="color: #5FB878;">上传成功</span>');
                  //tds.eq(2).html(''); //清空按钮操作
                  tds.find('.demo-delete').data('fileid', res.FileId);
                  return delete this.files[index]; //删除文件队列已经上传成功的文件
              }
              this.error(index, upload);
          }
          , error: function (index, upload) {
              var tr = demoListView.find('tr#upload-' + index)
              , tds = tr.children();
              tds.eq(1).html('<span style="color: #FF5722;">上传失败</span>');
              tds.eq(2).find('.demo-reload').removeClass('layui-hide'); //显示重传
          }
        });
    }

    //删除附件
    oInit.Delete = function (file_id, func) {
        $.ajax({
            type: "post",
            url: Root + 'EPHonor/DeleteEPFile',
            data: { file_id: file_id },
            success: function (data) {
                if (data.SubmitResult) {
                    toastr.success("删除成功!");
                } else {
                    dialog.danger('操作失败！Error Message:' + data.Message);
                }
            },
            error: function () {
                dialog.danger('操作失败！请重试或者联系管理员');
            },
            complete: function () {
                func();
            }
        });
    }

    return oInit;
}